package com.koko.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.util.Base64;
import java.util.UUID;

public class Base64Util {
    /**
     * 将图片文件转换为Base64编码的字符串，并添加适当的前缀。
     *
     * @param imagePath 图片文件的路径
     * @return Base64编码的字符串，如果过程中出现错误则返回null
     */
    public static String convertImageToBase64(String imagePath) {
        File file = new File(imagePath);
        String prefix = "data:" + getMimeType(imagePath) + ";base64,";
        try (FileInputStream imageInFile = new FileInputStream(file)) {
            byte imageData[] = new byte[(int) file.length()];
            imageInFile.read(imageData);
            String base64Image = Base64.getEncoder().encodeToString(imageData);
            return prefix + base64Image;
        } catch (IOException e) {
            System.out.println("Image to Base64 conversion error: " + e.getMessage());
            return null;
        }
    }

    /**
     * 根据文件路径获取MIME类型。
     *
     * @param filePath 文件路径
     * @return MIME类型字符串
     */
    private static String getMimeType(String filePath) {
        String mimeType = "";
        try {
            mimeType = Files.probeContentType(new File(filePath).toPath());
        } catch (IOException e) {
            System.out.println("Failed to determine MIME type: " + e.getMessage());
        }
        return mimeType != null ? mimeType : "application/octet-stream";
    }

    /**
     * 根据base64编码文件获取MIME类型
     *
     * @param base64DataUri
     * @return 随机文件名
     */
    public static String getFileName(String base64DataUri) {
        if (base64DataUri != null && base64DataUri.startsWith("data:") && base64DataUri.contains(";base64,")) {
            String suffix = base64DataUri.substring(11, base64DataUri.indexOf(';'));
            String fileName = UUID.randomUUID().toString() + "." + suffix;
            return fileName;
        }
        return null;
    }


    /**
     * 将Base64编码的字符串解码并保存为图片文件。
     *
     * @param base64String Base64编码的图像字符串（包含MIME类型前缀）
     * @param outputPath 输出图片的路径
     * @return 成功返回true，否则返回false
     */
    public static boolean convertBase64ToImage(String base64String, String outputPath) {
        try (FileOutputStream imageOutFile = new FileOutputStream(outputPath)) {
            // 移除Base64前缀
            String dataPart = base64String.substring(base64String.indexOf(",") + 1);
            byte[] imageByteArray = Base64.getDecoder().decode(dataPart);
            imageOutFile.write(imageByteArray);
            return true;
        } catch (IOException e) {
            System.out.println("Base64 to image conversion error: " + e.getMessage());
            return false;
        }
    }

    public static String convertBufferedImageToBase64(BufferedImage image) {
        String prefix = "data:image/jpg;base64,";
        //将图片写出
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 使用Base64编码图片字节
        byte[] imageBytes = outputStream.toByteArray();
        return prefix + Base64.getEncoder().encodeToString(imageBytes);
    }
}
